package jp.sourceforge.akjrcp.akj_betas.wizards;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.dvdstyler.DVDStylerData;
import jp.sourceforge.akjrcp.dvdstyler.DVDStylerTitle;
import jp.sourceforge.akjrcp.flvtools.basic.SimpleView;
import jp.sourceforge.akjrcp.flvtools.dvdstyler.DVDStylerPage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.wizard.Wizard;
import org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;


	public class DVDStylerExportWizard extends Wizard
	{
		public static Log log=LogFactory.getLog(DVDStylerExportWizard.class);
		
	    private FileListWizardPage page1;
	    private ChooseOutputWizardPage page2;
	    

	    public DVDStylerExportWizard()
	    {
	        super();
	        this.setWindowTitle(Messages.getString("dvdstyler.export_wizard_title"));
	        setNeedsProgressMonitor(false);
	    }

	    public void addPages()
	    {
	    	
	    	SimpleView.log.info("addpage");
	        page1 = new FileListWizardPage("file list");
	       
	        page2 = new ChooseOutputWizardPage("output file");
	        addPage(page1);
	        addPage(page2);
	      
	    }

	    public boolean performFinish()
	    {
	    	DVDStylerData dvd=new DVDStylerData();
	    	if(page2.getVersion()==1){
	    		dvd.setFormat(DVDStylerData.VERSION_1);
	    	}
	    	//add titles;
	    	int maxvideo=25;
	    	int current=0;
	    	int titleset=1;
	    	File files[]=page1.getFileList();
	    	for (int i = 0; i < files.length; i++) {
	    		boolean nextTitleset=false;
	    		current++;
				if(current==maxvideo){
					current=0;
					titleset++;
					//ignore last video
					if(i!=files.length-1){
						nextTitleset=true;
					}
				}
				
	    		String command=DVDStylerData.createJumpTitle(i+1+1);//because i start 0 & must go next
	    		
	    		if(nextTitleset){
	    			command=DVDStylerData.createJumpTitle(titleset,1);//anytime go first 1
	    		}
	    		
	    		if(i==files.length-1){
	    			if(page2.isLoop()){
	    			command=DVDStylerData.createJumpVmgmMenu(1);//go back.
	    			}else{
	    			command="";//stop
	    			}
	    		}
				DVDStylerTitle title=new DVDStylerTitle(files[i].getAbsolutePath(),command);
				dvd.addTitle(title);
				
				if(nextTitleset){
					dvd.addTitleset();
				}
	    	}
	    	Document doc=dvd.toDocument();
	    	String path=page2.getSavePath();
	    	log.info("save path:"+path);
	    	
	    	
	    	writeXML(doc,path);
	    	if(page2.isLaunch()){
	    		launchDVDStyler(path);
	    	}
	        return true;
	    }
	    
	    private void launchDVDStyler(String path) {
			Runtime runtime=Runtime.getRuntime();
			String dvdstylerpath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(DVDStylerPage.DVDSTYLER_PATH);
			if(dvdstylerpath.length()>0){
			File exe=new File(dvdstylerpath);
			if(exe.exists()){
			String args[]=new String[]{dvdstylerpath,path};
			@SuppressWarnings("unused")
			Process process;
			try {
				process = runtime.exec(args);
				//maybe not need.
				//int result=process.waitFor();
				//log.info(""+result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}/* catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			
			}else{
				log.warn("dvd styler not found:"+dvdstylerpath);
			}
			}else{
				log.warn("dvd styler path is empty");
			}
		}

		public void writeXML(Document document,String path){
	    	  DVDStylerExportWizard.log.info(path);
	    	  DVDStylerExportWizard.log.info(document);
	          XMLSerializer serial=new XMLSerializer();
	          Writer writer=null;
	          try {
	        	 OutputFormat format=new OutputFormat();
	        	 format.setEncoding("UTF-8");
	        	 format.setLineSeparator("\r\n");
	        	 format.setIndenting(true);
	        	 serial.setOutputFormat(format);
	        	 writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)),"UTF-8"));
				 serial.setOutputCharStream(writer);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				 DVDStylerExportWizard.log.info(e1.getMessage());
				e1.printStackTrace();
			}
	          try {
	        	  DVDStylerExportWizard.log.info("start serialize");
				serial.serialize(document);
				 DVDStylerExportWizard.log.info("end serialize");
				writer.flush();
				writer.close();
			} catch (IOException e) {
				DVDStylerExportWizard.log.info(e.getMessage());
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    
	    
	}
